import React from 'react'
import PropTypes from 'prop-types'

class Upload extends React.PureComponent{
    constructor(props){
        super(props)
        this.uploadRef = React.createRef()
        this.state = {
            fileName: ''
        }
    }
    upload(){
        this.uploadRef.current.click()
    }
    clearFiles(){
        this.uploadRef.current.value = ''
        if(this.props.showFileName){
            this.setState({
                fileName: ''
            })
        }
    }
    onChange(){
        if(this.uploadRef.current.files.length){
            if(this.props.onChange){
                this.props.onChange(this.uploadRef.current.files)
            }
            if(this.props.showFileName){
                this.setState({
                    fileName: this.uploadRef.current.files[0].name
                })
            }
        }
    }
    render(){
        return(
            <div style={{ display: 'inline-block', cursor: 'pointer', ...this.props.style }} onClick={ this.upload.bind(this) }>
                <input type="file" multiple={ this.props.multiple } ref={ this.uploadRef } onClick={ e => { e.stopPropagation(); this.clearFiles() } } onChange={ this.onChange.bind(this) } style={{ display: 'none' }} />
                { this.props.children }
                {
                    this.props.showFileName
                    ?
                    <span style={{ display: 'inline-block', marginLeft: '10px', fontSize: '14px', wordBreak: 'break-all' }}>{ this.state.fileName }</span>
                    :
                    null
                }
            </div>
        )
    }
}

Upload.propTypes = {
    onChange: PropTypes.func,
    children: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
    value: PropTypes.string,
    style: PropTypes.object,
    showFileName: PropTypes.bool,
    multiple: PropTypes.bool
}

export {
    Upload
}